package cn.school.demo.ui.my_answer

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentMyAnswerBinding
import cn.school.demo.pojo.Subject
import cn.school.demo.pojo.Test
import cn.school.demo.ui.answer.AnswerViewModel
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.mylhyl.circledialog.CircleDialog
import java.time.LocalDateTime

class MyAnswerFragment : Fragment() {

    private lateinit var viewModel: MyAnswerViewModel
    private lateinit var binding: FragmentMyAnswerBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(MyAnswerViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my_answer, container, false)

        val navView: BottomNavigationView = binding.navView
        val navController = findNavController()
        navView.setupWithNavController(navController)
        requireActivity().window.apply {
            statusBarColor = Color.argb(1, 249, 249, 249)
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
        init()
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun init() {
        viewModel.getSubjectListByTrueTime().observe(viewLifecycleOwner) {
            if (it.size > 0) {
                binding.fragmentMyAnswerProgressBar.visibility = View.GONE
                binding.fragmentMyAnswerNoData.visibility = View.GONE
                viewModel.updateAnswerList(it)
                binding.fragmentMyAnswerRecycleView.apply {
                    adapter?.notifyDataSetChanged() ?: let {
                        adapter = MyAnswerAdapter(viewModel.answerList)
                        layoutManager = LinearLayoutManager(requireContext())
                    }
                }
            } else {
                binding.fragmentMyAnswerProgressBar.visibility = View.GONE
                binding.fragmentMyAnswerNoData.visibility = View.VISIBLE
            }
        }
    }

    private inner class MyAnswerHolder(view: View) : RecyclerView.ViewHolder(view) {
        private lateinit var subject: Subject
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.list_item_my_answer_title)
        private val button =
            itemView.findViewById<Button>(R.id.list_item_my_answer_button)
        private val startTime =
            itemView.findViewById<TextView>(R.id.list_item_my_answer_startTime)
        private val endTime =
            itemView.findViewById<TextView>(R.id.list_item_my_answer_endTime)

        @SuppressLint("NewApi", "SetTextI18n")
        fun bind(subject: Subject) {
            this.subject = subject
            titleTextView.text = this.subject.subjectTitle
            startTime.text = "开始时间:${
                this.subject.startTime.subSequence(
                    0,
                    10
                )
            } ${this.subject.startTime.subSequence(11, 19)}"
            endTime.text = "结束时间:${this.subject.endTime.subSequence(0, 10)} ${
                this.subject.endTime.subSequence(
                    11,
                    19
                )
            }"
            button.setOnClickListener {
                MyApplication.signId = subject.signid
                AnswerViewModel().getSubjectListById().observe(viewLifecycleOwner) { list ->
                    if (list.size == 0) {
                        list.add(
                            Subject(
                                1,
                                1,
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                LocalDateTime.now().toString(),
                                LocalDateTime.now().toString(),
                                1
                            )
                        )
                        MyApplication.apply {
                            isSubject = false
                            testList.clear()
                            testList.add(Test(-1, "", "", "", "", "", "", ""))
                            this.subjectList.apply {
                                clear()
                                addAll(list)
                            }
                        }
                        CircleDialog.Builder().setText("您已参与！").setNegative("确定", null)
                            .show(parentFragmentManager)
                    } else {
                        MyApplication.apply {
                            isSubject = true
                            testList.clear()
                            testList.add(Test(-1, "", "", "", "", "", "", ""))
                            this.subjectList.apply {
                                clear()
                                addAll(list)
                            }
                            val map =
                                mapOf("title" to subject.subjectTitle, "introduction" to "测一测你自己吧！")
                            answerTopic = subject.subjectTitle
                            val bundle: Bundle = bundleOf(Pair("map", GsonUtils.toJson(map)))
                            navigateThing["AnswerMain"] =
                                R.id.action_AnswerMain_to_My_Answer.toString()
                            navigateThing["Answer"] =
                                R.id.action_Answer_to_My_Answer.toString()
                            goto(
                                R.id.action_My_Answer_to_AnswerEntity,
                                findNavController(),
                                parentFragmentManager,
                                bundle
                            )
                        }
                    }

                }
            }
        }

    }

    private inner class MyAnswerAdapter(var subjectList: MutableList<Subject>) :
        RecyclerView.Adapter<MyAnswerHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAnswerHolder {
            val view = layoutInflater.inflate(R.layout.list_item_my_answer, parent, false)
            return MyAnswerHolder(view)
        }

        override fun onBindViewHolder(holder: MyAnswerHolder, position: Int) {
            val subjectList = subjectList[position]
            holder.bind(subjectList)
        }

        override fun getItemCount() = subjectList.size

    }
}